package com.janal.controller.Modify;

import com.janal.model.user.User;
import com.janal.service.modify.ModifyService;
import com.janal.service.modify.ModifyServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class ModifyPasswordServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、获取前端传来的原密码和新密码
        HttpSession session = req.getSession();
        String usercode = (String) session.getAttribute("usercode");
        String password = (String) session.getAttribute("password");
        String oldPassword = req.getParameter("oldPassword");
        String newPassword1 = req.getParameter("newPassword1");
        String newPassword2 = req.getParameter("newPassword2");

        //2、判读原密码是否正确
        if(!password.equals(oldPassword)){
            System.out.println(password);
            System.out.println(oldPassword);
            req.setAttribute("modifyPasswordError", "密码错误！");
            req.getRequestDispatcher("modifyPassword.jsp").forward(req, resp);
        }else{
            //3、判断两次新密码是否相同并且不为空
            if("".equals(newPassword1) || "".equals(newPassword2)){
                req.setAttribute("modifyPasswordError", "密码不能为空！");
                req.getRequestDispatcher("modifyPassword.jsp").forward(req, resp);
            }else if(newPassword1.equals(newPassword2)){
                req.setAttribute("modifyPasswordError", "两次密码输入不相同！");
                req.getRequestDispatcher("modifyPassword.jsp").forward(req, resp);
            }else{
                //4、验证通过，调用service方法更新数据库
                User user = new User(usercode,newPassword1);
                ModifyService ms = new ModifyServiceImpl();
                if(ms.modifyPassword(user)){
                    resp.sendRedirect("/p/success.jsp");
                }else{
                    req.setAttribute("modifyPasswordError", "输入失败！");
                    req.getRequestDispatcher("modifyPassword.jsp").forward(req, resp);
                }
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
